<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends CommonController {
	public $appkey = MOB_APPK;
	public $member_field;

	/**
     * [token token验证]
     * @return [type] [json]
     */
	public function __construct(){
		//$this->token();
        $this->member_field =  'member_id,member_passwd,member_email,member_email_bind,member_truename,member_avatar,member_name,member_mobile,member_login_time,member_old_login_time,member_login_ip,member_old_login_ip';
	}

    /**
     * 同步环新用户
     */
    public function emchat_isuser($member_id){
        $meber = M('member');
        $data = $meber->find($member_id);
        $username = $data['member_name'];
        $password = $data['member_passwd'];
       // $getuser = parent::emchat_getUser($username);
        $result = parent::emchat_createUser($username,$password);

    }

	/**
     * [第三方登录]
     * @return [type] [json]
     */
	public function otherlogin(){
		$openid = I('post.openid') or returnApiError(1,'缺少openid');
        $typeid = I('post.typeid') or returnApiError(1,'缺少typeid');   // 1qq 2新浪  3微信
        $token = I('post.access_token') or returnApiError(1,'缺少access_token');
        $appid = I('post.appid') or returnApiError(1,'缺少appid');
        if($appid == 1) $appid = '1105250033';
        if($appid == 2) $appid = '1105403658';
       // $token = "C54A56E7CAF95F756D23C6E030EB712F";
       // $openid = "4615E3C9AAF2265E9658300A9DAF9B77";
        if($typeid == 1){
            $this->qqlogin($openid,$token,$appid);
        }
        if($typeid == 2){
            $this->sinalogin($openid,$token);
        }
        if($typeid == 3){
            $this->wechatlogin($openid,$token);
        }
	}

    /**
     * qq登录
     * @param $openid
     * @param $token
     */
    public function qqlogin($openid,$token,$appid){

        $url = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=$appid&access_token=$token&openid=$openid&format=json";
        $result =  $this->getRequest($url);
        $result_arr = json_decode($result,true);

        if($result_arr['ret'] == 0){
            $Model = M('Member');
            $map['member_qqopenid'] = $openid;
            $data = $Model->field($this->member_field)->where($map)->find();

            if(!$data) {
                $user['info'] = $result;
                $user['openid'] = $openid;
                $user['typeid'] = 1;
                $user['is_bind'] = 0;
                $user['figureurl'] = $result_arr['figureurl_qq_2'];
                $user['nickname'] = $result_arr['nickname'];
                returnApiSuccess('ok',$user);
            }

            $token = md5($data['member_id'].$data['member_name']);
            $data['is_bind'] = 1;
            $data['token'] = $token;

            $save['member_login_time'] = time();
            $save['member_old_login_time'] = $data['member_old_login_time'];
            $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $save['member_old_login_ip'] = $data['member_login_ip'];
            $condition['member_qqopenid'] = $openid;
            $Model->where($condition)->save($save);
            $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$data['member_avatar'];

            //赠送积分
            $old_time = date("Ymd",$data['member_login_time']);
            $new_time = date("Ymd");
            if($old_time!=$new_time){
            $pointlog = D('PointsLog'); 
            $insertarr["pl_memberid"] =$data['member_id'];
            $insertarr["pl_membername"] =$data['member_name'];
            $points = $pointlog->insert("login",$insertarr);
            }
            $this->emchat_isuser($data['member_id']);
            returnApiSuccess('ok',$data);
            
        }else{
            returnApiError(1,$result_arr['msg']);
        }

    }

    /**
     * 新浪登录
     */
    public function sinalogin($openid,$token){
        $url = "https://api.weibo.com/2/users/show.json?access_token=$token&uid=$openid";
        $result =  $this->getRequest($url);
        $result_arr = json_decode($result,true);

        if($result_arr['errcode'] == 0){
            $Model = M('Member');
            $map['member_sinaopenid'] = $openid;
            $data = $Model->field($this->member_field)->where($map)->find();

            if(!$data) {
                $user['info'] = $result;
                $user['openid'] = $openid;
                $user['typeid'] = 1;
                $user['is_bind'] = 0;
                $user['figureurl'] = $result_arr['avatar_large'];
                $user['nickname'] = $result_arr['name'];
                returnApiSuccess('ok',$user);
            }

            $token = md5($data['member_id'].$data['member_name']);
            $data['is_bind'] = 1;
            $data['token'] = $token;

            $save['member_login_time'] = time();
            $save['member_old_login_time'] = $data['member_old_login_time'];
            $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $save['member_old_login_ip'] = $data['member_login_ip'];
            $condition['member_sinaopenid'] = $openid;
            $Model->where($condition)->save($save);
            $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$data['member_avatar'];
             //赠送积分
            $old_time = date("Ymd",$data['member_login_time']);
            $new_time = date("Ymd");
            if($old_time!=$new_time){
            $pointlog = D('PointsLog'); 
            $insertarr["pl_memberid"] =$data['member_id'];
            $insertarr["pl_membername"] =$data['member_name'];
            $points = $pointlog->insert("login",$insertarr);
            }
            $this->emchat_isuser($data['member_id']);
            returnApiSuccess('ok',$data);
        }else{
            returnApiError(1,$result_arr['error']);
        }
        //returnApiError(1,'敬请期待');
    }

    /**
     * 微信登录
     */
    public function wechatlogin($openid,$token){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid";
        $result =  $this->getRequest($url);
        $result_arr = json_decode($result,true);
        if($result_arr['errcode'] == 0){
            $Model = M('Member');
            $map['weixin_unionid'] = $openid;
            $data = $Model->field($this->member_field)->where($map)->find();

            if(!$data) {
                $user['info'] = $result;
                $user['openid'] = $openid;
                $user['typeid'] = 3;
                $user['is_bind'] = 0;
                $user['figureurl'] = $result_arr['headimgurl'];
                $user['nickname'] = $result_arr['nickname'];
                returnApiSuccess('ok',$user);
            }

            $token = md5($data['member_id'].$data['member_name']);
            $data['is_bind'] = 1;
            $data['token'] = $token;

            $save['member_login_time'] = time();
            $save['member_old_login_time'] = $data['member_login_time'];
            $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $save['member_old_login_ip'] = $data['member_login_ip'];
            $condition['weixin_unionid'] = $openid;
            $Model->where($condition)->save($save);
            $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$data['member_avatar'];
             //赠送积分
            $old_time = date("Ymd",$data['member_login_time']);
            $new_time = date("Ymd");
            if($old_time!=$new_time){
            $pointlog = D('PointsLog'); 
            $insertarr["pl_memberid"] =$data['member_id'];
            $insertarr["pl_membername"] =$data['member_name'];
            $points = $pointlog->insert("login",$insertarr);
            }
            $this->emchat_isuser($data['member_id']);
            returnApiSuccess('ok',$data);
        }else{
            returnApiError(1,$result_arr['errmsg']);
        }

       // returnApiError(1,'敬请期待');


    }

    /**
     * 绑定账号
     */
    public function bind(){
        $typeid = I('post.typeid')  or returnApiError(1,'缺少type');
        $openid = I('post.openid')  or returnApiError(1,'缺少openid');
        $userinfo = I('post.userinfo')  or returnApiError(1,'缺少userinfo');
        $tel = I('post.tel')  or returnApiError(1,'缺少tel');
        $code = I('post.code')  or returnApiError(1,'缺少code');

        $Model = M('Member');
        $where['member_mobile'] = $tel;
        $data = $Model->where($where)->find();
        if(!$data)  returnApiError(1,'账号不存在，请先注册');
        if($typeid == 1){
            if($data['member_qqopenid']){
                returnApiError(40003,'手机号已被绑定');
            }
        }

        if($typeid == 2){
            if($data['member_qqopenid']){
                returnApiError(40003,'手机号已被绑定');
            }
        }

        if($typeid == 3){
            if($data['member_sinaopenid']){
                returnApiError(40003,'手机号已被绑定');
            }
        }


        $check = $data ? 2 : 1;

        //短信验证
        $api = 'https://webapi.sms.mob.com/sms/verify';
        $arr = array(
            'appkey' => $this->appkey,
            'phone' => $tel,
            'zone' => '86',
            'code' => $code,
        );
        $response = $this->postRequest($api, $arr);
        $param = json_decode($response,true);
        $status= $param['status'];
        if($status != 200){
            returnApiError($status,'短信校验失败');
        }
        if($typeid == 1){
            $this->qqbind($openid,$userinfo,$tel,$check);
        }
        if($typeid == 2){
            $this->sinabind($openid,$userinfo,$tel,$check);
        }
        if($typeid == 3){
            $this->wxbind($openid,$userinfo,$tel,$check);
        }

    }

    /**
     * 登录后绑定账号
     */
    public function userbind(){
        $typeid = I('post.typeid')  or returnApiError(1,'缺少type');
        $openid = I('post.openid')  or returnApiError(1,'缺少openid');
        $userinfo  = "";
        $uid = I('post.uid',0,'intval') or returnApiError(1,'缺少uid');;

        $Model = M('Member');
        $data = $Model->find($uid);
        if(!$data) returnApiError(1,'用户不存在');;
        $tel = $data['member_mobile'];

        if($typeid == 1){
            $this->qqbind($openid,$userinfo,$tel,2);
        }
        if($typeid == 2){
            $this->sinabind($openid,$userinfo,$tel,2);
        }
        if($typeid == 3){
            $this->wxbind($openid,$userinfo,$tel,2);
        }

    }


    public function qqbind($openid,$userinfo,$tel,$check){
        $Model = M('Member');
        if($check == 2){
            $where['member_mobile'] = $tel;
            $result = $Model->field($this->member_field)->where($where)->find();
            if(!$result) returnApiError(1,'账号不存在');

            $save['member_qqopenid'] = $openid;
            $save['member_qqinfo'] = urlencode($userinfo);
            $save['member_login_time'] = time();
            $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $save['member_old_login_ip']= $result['member_login_ip'];
            $condition['member_mobile'] = $tel;
            $Model->where($where)->save($save);

            $user_token = md5($result['member_id'].$result['member_name']);
            $result['token'] = $user_token;

        }else{
            $add['member_qqopenid'] = $openid;
            $add['member_qqinfo'] = urlencode($userinfo);
            $add['member_name'] = time().rand('100','999');
            $add['member_time'] = time();
            $add['member_login_time'] = time();
            $add['member_mobile'] = $tel;
            $add['member_mobile_bind'] = 1;
            $add['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $res = $Model->add($add);
            $last_id = $res;
            $result = $Model->field($this->member_field)->where("member_id = $last_id")->find();
            $user_token = md5($result['member_id'].$result['member_name']);
            $result['token'] = $user_token;
        }

        $result['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$result['member_avatar'];
        $result['member_qqinfo'] = urldecode($result['member_qqinfo']);
        returnApiSuccess('ok',$result);
    }

    public function sinabind($openid,$userinfo,$tel,$check){
        $Model = M('Member');
        if($check == 2){
            $where['member_mobile'] = $tel;
            $result = $Model->field($this->member_field)->where($where)->find();
            if(!$result) returnApiError(1,'账号不存在');

            $save['member_sinaopenid'] = $openid;
            $save['member_sinainfo'] = urlencode($userinfo);
            $save['member_login_time'] = time();
            $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $save['member_old_login_ip']= $result['member_login_ip'];
            $condition['member_mobile'] = $tel;
            $Model->where($where)->save($save);

            $user_token = md5($result['member_id'].$result['member_name']);
            $result['token'] = $user_token;

        }else{
            $add['member_sinaopenid'] = $openid;
            $add['member_sinainfo'] = urlencode($userinfo);
            $add['member_name'] = time().rand('100','999');
            $add['member_time'] = time();
            $add['member_login_time'] = time();
            $add['member_mobile'] = $tel;
            $add['member_mobile_bind'] = 1;
            $add['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $res = $Model->add($add);
            $last_id = $res;
            $result = $Model->field($this->member_field)->where("member_id = $last_id")->find();
            $user_token = md5($result['member_id'].$result['member_name']);
            $result['token'] = $user_token;
        }
        $result['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$result['member_avatar'];
        $result['member_sinainfo'] = urldecode($result['member_sinainfo']);
        returnApiSuccess('ok',$result);
    }


    public function wxbind($openid,$userinfo,$tel,$check){
        $Model = M('Member');
        if($check == 2){
            $where['member_mobile'] = $tel;
            $result = $Model->field($this->member_field)->where($where)->find();
            if(!$result) returnApiError(1,'账号不存在');

            $save['weixin_unionid'] = $openid;
            $save['weixin_info'] = urlencode($userinfo);
            $save['member_login_time'] = time();
            $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $save['member_old_login_ip']= $result['member_login_ip'];
            $condition['member_mobile'] = $tel;
            $Model->where($where)->save($save);

            $user_token = md5($result['member_id'].$result['member_name']);
            $result['token'] = $user_token;

        }else{
            $add['weixin_unionid'] = $openid;
            $add['weixin_info'] = urlencode($userinfo);
            $add['member_name'] = time().rand('100','999');
            $add['member_time'] = time();
            $add['member_login_time'] = time();
            $add['member_mobile'] = $tel;
            $add['member_mobile_bind'] = 1;
            $add['member_login_ip']= $_SERVER["REMOTE_ADDR"];
            $res = $Model->add($add);
            $last_id = $res;
            $result = $Model->field($this->member_field)->where("member_id = $last_id")->find();
            $user_token = md5($result['member_id'].$result['member_name']);
            $result['token'] = $user_token;
        }

        $result['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$result['member_avatar'];
        $result['weixin_info'] = urldecode($result['weixin_info']);
        returnApiSuccess('ok',$result);
    }

	/**
     * [tellogin 手机快捷登录]
     * @return [type] [json]
     */
	public function tellogin(){
		$code = $_POST['code'];
		$tel = $_POST['tel'];
		if(!$code) returnApiError(1,'请填写验证码');
		if(!$tel) returnApiError(1,'请填写手机号');
		
		$Model = M('Member');
		$where['member_mobile'] = $tel;
		$data = $Model->field($this->member_field)->where($where)->find();
		if(!$data) returnApiError(40006,'用户不存在');
		
		//短信验证
		$api = 'https://webapi.sms.mob.com/sms/verify';
		$arr = array(
			'appkey' => $this->appkey,
			'phone' => $tel,
			'zone' => '86',
			'code' => $code,
		);
		$response = $this->postRequest($api, $arr);
		$param = json_decode($response,true);
		$status= $param['status'];
		if($status != 200){
			returnApiError($status,'短信校验失败');
		}
		$token = md5($data['member_id'].$data['member_name']);
		$data['token'] = $token;
		
		$save['member_login_time'] = time();
		$save['member_old_login_time'] = $data['member_login_time'];
		$save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
		$save['member_old_login_ip']= $data['member_login_ip'];
		$condition['member_mobile'] = $tel;
		$Model->where($condition)->save($save);
        $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$data['member_avatar'];
           //赠送积分
            $old_time = date("Ymd",$data['member_login_time']);
            $new_time = date("Ymd");
            if($old_time!=$new_time){
            $pointlog = D('PointsLog'); 
            $insertarr["pl_memberid"] =$data['member_id'];
            $insertarr["pl_membername"] =$data['member_name'];
            $points = $pointlog->insert("login",$insertarr);
            }
        $this->emchat_isuser($data['member_id']);
		returnApiSuccess('ok',$data);
		
	}
	
	/**
     * [login 自动登录验证]
     * @return [type] [json]
     */
	public function autologin(){
		$token = I('post.user_token');
		$username = trim(I('post.username'));
		if(!$token) returnApiError(1,'缺少token参数');
		if(!$username) returnApiError(1,'缺少username参数');
		
		$Model = M('Member');
		$where['member_name'] = $username;
		$data = $Model->field($this->member_field)->where($where)->find();

		if(!$data) returnApiError(1,'参数错误');
		$data_token = md5($data['member_id'].$data['member_name']);
		if($token != $data_token) returnApiError(1,'token参数错误');
		$time = $data['member_login_time'] + 604800;
		if($time < time()) returnApiError(40007,'user_token过期,请重新登录');
        $save['member_login_time'] = time();
        $save['member_old_login_time'] = $data['member_login_time'];
        $save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
        $save['member_old_login_ip']= $data['member_login_ip'];
        $condition['member_name'] = $username;
        $Model->where($condition)->save($save);
		$data['token'] = $token;
        $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$data['member_avatar'];
                //赠送积分
            $old_time = date("Ymd",$data['member_login_time']);
            $new_time = date("Ymd");
            if($old_time!=$new_time){
                $pointlog = D('PointsLog'); 
                $insertarr["pl_memberid"] =$data['member_id'];
                $insertarr["pl_membername"] =$data['member_name'];
                $points = $pointlog->insert("login",$insertarr);
            }
        $this->emchat_isuser($data['member_id']);
		returnApiSuccess('ok',$data);
	}
	
	/**
     * [login 用户登录]
     * @return [type] [json]
     */
	public function login(){
		//参数接收
		$username = trim(I('post.username'));
		$password = trim(I('post.password'));
		$strlen_user = strlen($username);
		
		//数据验证
		if(empty($username)) returnApiError(1,'用户名必须填写');
		if(empty($password)) returnApiError(1,'密码必须填写');
		if($strlen_user >= 50) returnApiError(1,'用户名长度超过限制');
		
		$Model = M('Member');
                $pointlog = D('PointsLog'); 
		$tel_where['member_mobile'] = $username;
		$tel_where['member_passwd'] = md5($password);
		$name_where['member_name'] = $username;
		$name_where['member_passwd'] = md5($password);
		
		//手机号登录验证
		$tel_data = $Model->field($this->member_field)->where($tel_where)->find();

		$user_token = md5($tel_data['member_id'].$tel_data['member_name']);

		if($tel_data){   
            $tel_data['token'] = $user_token;
			$save['member_login_time'] = time();
			$save['member_old_login_time'] = $tel_data['member_login_time'];
			$save['member_old_login_ip']= $tel_data['member_login_ip'];
			$save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
			$condition['member_name'] = $tel_data['member_name'];
			$Model->where($condition)->save($save);
            $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$tel_data['member_avatar'];
                    //赠送积分
                    $old_time = date("Ymd",$tel_data['member_login_time']);
                    $new_time = date("Ymd");
                    if($old_time!=$new_time){
                        $insertarr["pl_memberid"] =$tel_data['member_id'];
                        $insertarr["pl_membername"] =$tel_data['member_name'];
                        $points = $pointlog->insert("login",$insertarr); 
                    }
            $this->emchat_isuser($tel_data['member_id']);
			returnApiSuccess('ok',$tel_data);
		} 
		
		//账号登录验证
		$name_data = $Model->field($this->member_field)->where($name_where)->find();

		if(!$name_data) returnApiError(40005,'用户名或密码不正确');
		$user_token = md5($name_data['member_id'].$name_data['member_name']);
		$name_data['token'] = $user_token;
		$save['member_login_time'] = time();
                $save['member_old_login_time'] = $name_data['member_login_time'];
		$save['member_old_login_ip']= $name_data['member_login_ip'];
		$save['member_login_ip']= $_SERVER["REMOTE_ADDR"];
		$condition['member_name'] = $name_data['member_name'];
		$Model->where($condition)->save($save);
        $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$name_data['member_avatar'];
                //赠送积分
            $old_time = date("Ymd",$name_data['member_login_time']);
            $new_time = date("Ymd");
            if($old_time!=$new_time){
                
                $insertarr["pl_memberid"] =$name_data['member_id'];
                $insertarr["pl_membername"] =$name_data['member_name'];
                $points = $pointlog->insert("login",$insertarr); 
            }
        $this->emchat_isuser($name_data['member_id']);
		returnApiSuccess('ok',$name_data);
        }
	/**
     * [getpassword 找回密码]
     * @return [type] [json]
     */
	public function getpassword(){
		//参数接收
		$password = trim(I('post.password'));
		$repassword = trim(I('post.repassword'));
		$code = trim(I('post.code'));
		$tel = I('post.tel');
		
			
		//数据验证
		if(empty($password)) returnApiError(1,'密码必须填写');
		if(empty($repassword)) returnApiError(1,'确认密码必须填写');
		if(empty($tel)) returnApiError(1,'手机号必须填写');
		if(empty($code)) returnApiError(1,'验证码必须填写');
		if($password != $repassword) returnApiError(1,'两次密码不一致');
		
		//验证用户	
		$Model = M('Member');
		$data = $Model->where("member_mobile = $tel")->find();
		if(!$data) returnApiError(40006,'用户不存在');
		
		//短信验证
		$api = 'https://webapi.sms.mob.com/sms/verify';
		$arr = array(
			'appkey' => $this->appkey,
			'phone' => $tel,
			'zone' => '86',
			'code' => $code,
		);
		$response = $this->postRequest($api, $arr);
		$param = json_decode($response,true);
		$status= $param['status'];
		if($status != 200){
			returnApiError($status,'短信校验失败');
		}
		$save['member_passwd'] = md5($password);
		$condition['member_mobile'] = $tel;
		$Model->where($condition)->save($save);
        parent::emchat_resetPassword($data['member_name'],md5($password));
		returnApiSuccess('ok');
	}
	
	/**
     * [reg 用户注册]
     * @return [type] [json]
     */
	public function register(){
		//参数接收
		
		$password = trim(I('post.password'));
		$repassword = trim(I('post.repassword'));
		$code = trim(I('post.code'));
		$tel = I('post.tel');
		
		
		//数据验证
		if(empty($password)) returnApiError(1,'密码必须填写');
		if(empty($repassword)) returnApiError(1,'确认密码必须填写');
		if(empty($tel)) returnApiError(1,'手机号必须填写');
		if(empty($code)) returnApiError(1,'验证码必须填写');
		if($password != $repassword) returnApiError(1,'两次密码不一致');
	
		//验证是否被注册过	
		$Model = M('Member');
		if($Model->where("member_mobile = $tel")->find()) returnApiError(1,'手机号已被注册');
		
		//短信验证
		$api = 'https://webapi.sms.mob.com/sms/verify';
		$arr = array(
			'appkey' => $this->appkey,
			'phone' => $tel,
			'zone' => '86',
			'code' => $code,
		);
		$response = $this->postRequest($api, $arr);
		$param = json_decode($response,true);
		$status= $param['status'];
		if($status != 200){
			returnApiError($status,'短信校验失败');
		}
		
		//写入数据
		$data['member_name'] = time().rand('100','999');
		$data['member_passwd'] = md5($password);
		$data['member_time'] = time();
		$data['member_login_time'] = time();
		$data['member_mobile'] = $tel;
		$data['member_mobile_bind'] = 1;
		$data['member_login_ip']= $_SERVER["REMOTE_ADDR"];
		$res = $Model->add($data);
        if(!$res) returnApiError(1,'注册失败');
        parent::emchat_createUser($data['member_name'],md5($password));
		$last_id = $res;
		$result = $Model->field($this->member_field)->where("member_id = $last_id")->find();
		$user_token = md5($result['member_id'].$result['member_name']);
		$result['token'] = $user_token;
        $result['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$result['member_avatar'];
                //赠送积分
     
                $pointlog = D('PointsLog'); 
                $insertarr["pl_memberid"] = $res;
                $insertarr["pl_membername"] = $data['member_name'];
                $points = $pointlog->insert("regist",$insertarr);

		returnApiSuccess('ok',$result);
	
	}
	
	/**
	 * 发起一个post请求到指定接口
	 * 
	 * @param string $api 请求的接口
	 * @param array $params post参数
	 * @param int $timeout 超时时间
	 * @return string 请求结果
	 */
	 function postRequest($api,$params = array(), $timeout = 30 ) {
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_URL, $api );
		// 以返回的形式接收信息
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
		// 设置为POST方式
		curl_setopt( $ch, CURLOPT_POST, 1 );
		curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params ) );
		// 不验证https证书
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
		curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
		curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
			'Accept: application/json',
		) ); 
		// 发送数据
		$response = curl_exec( $ch );
		// 不要忘记释放资源
		curl_close( $ch );
		return $response;
	 }

       /*
        * HTTP GET Request
        */
     public function getRequest($url) {
         $ch = curl_init($url) ;
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回

         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
         $output = curl_exec($ch) ;
         return $output;
    }
	
	/**
     * [address 用户地址信息]
     * @return [type] [json]
     */
	public function address(){
		$uid = I('post.uid',0,'intval');
		$address_id = I('post.address_id',0,'intval');
		if(!$uid)   returnApiError(1,'用户id参数错误');
		
		//实例化地址信息
		$Address = M('Address');
		$where['member_id'] = $uid;
		$field = "address_id,member_id,true_name,area_id,city_id,area_info,address,mob_phone,is_default,dlyp_id";
		if($address_id) $where['address_id'] = $address_id;
		if($address_id){
			$data = $Address->field($field)->where($where)->find();
		}else{
			$data = $Address->field($field)->where($where)->select();
		}
	
		if(!$data){
            returnArr('数据为空'); 
        }else{
            returnApiSuccess('ok',$data); 
        }
	}
	
	/**
     * [addaddress 新增用户收货地址]
     * @return [type] [json]
     */
	 public function addaddress(){
		$Model = D('Address');
		$result = $Model->validate();
		$data = $result['data'];
		$member_id = $data['member_id'];
		$userCount = $Model->where("member_id = $member_id")->count();
		if($userCount >= 20) returnApiError(1,'最多添加二十条地址');
		$data['is_default']=1;
		if($data['is_default'] == 1){
			 $default['is_default'] = 0;
			 $Model->where("member_id = $member_id")->save($default);
		}
	    if($aid = $Model->add($data)){
             $add_data = $Model->find($aid);
             unset($add_data['tel_phone']);
			 returnApiSuccess('ok',$add_data);
		}else{
			 returnApiError(1,'添加失败');
		}
		
	 }
	
	/**
     * [editddress 编辑用户收货地址]
     * @return [type] [json]
     */
	 public function editaddress(){
		 $Model = D("Address"); 
		 $result = $Model->validate();
		 $data = $result['data'];
		 $where = $result['where'];
		 $member_id = $data['member_id'];
		 if($data['is_default'] == 1){
			 $default['is_default'] = 0;
			 $Model->where("member_id = $member_id")->save($default);
		 }
		 if($Model->where($where)->save($data)){
			 returnApiSuccess('ok'); 
		 }else{
			 returnApiError(1,'编辑失败');
		 }
	 }
	 
	 
	/**
     * [deladdress  删除用户收货地址]
     * @return [type] [json]
     */
	 public function deladdress(){
		 $id = I('post.id',0,'intval');
		 $uid = I('post.uid',0,'intval');
		 if(!$id)  returnApiError(1,'id参数错误');
		 if(!$uid)  returnApiError(1,'用户id参数错误');
		 $Address = M("Address"); // 实例化User对象
		 $where['address_id'] = $id;
		 $where['member_id'] = $uid;
		 
		 $default_where['is_default'] = '1';
		 $default_where['address_id'] = $id;
		 
		 //判断是否默认地址
		 $default_data = $Address->where($default_where)->find();
		
		 if($Address->where($where)->delete()){
			 if($default_data){
				  $member_where['member_id'] = $uid;
				  $data = $Address->where($member_where)->find();
				  if($data){
					  $find_where['member_id'] = $uid;
					  $find_data = $Address->where($find_where)->find();
					  $find_id = $find_data['address_id'];
					  $condition['is_default'] = 1;
					  $Address->where("address_id = $find_id")->save($condition);	
				  }
				 	 
			}
		
			 returnApiSuccess('ok'); 
		 }else{
			 returnApiError(1,'删除失败');
		 }
		
	 }
        //收藏商品
        public function collect(){

         $uid = I('post.uid');
         $goods_id = I('post.goods_id');
         $is_collect = I("post.is_col");//是否取消
         $Member = M('Member');
         $goods  = M('goods');
         $favorites = M('favorites');
         $store  = M('store');
         
         //判断是否已经收藏
        $favorites_info = $favorites->where(array('fav_id'=>"$goods_id",'fav_type'=>'goods','member_id'=>"$uid"))->find();
//        if(!empty($favorites_info)){
//            returnApiError(1,'已经收藏！');
//        }
         if($is_collect==2){
             if(!empty($favorites_info)){
                $favorites->where('log_id='.$favorites_info['log_id'])->delete();
                $goods ->where('goods_id='.$goods_id)->setDec('goods_collect',1);
             }
            returnApiError(2,'取消收藏！');
         }
        $goods_info = $goods->field("goods_id as fav_id,store_id,store_name,gc_id,goods_name,goods_image,goods_promotion_price as log_price")->where(array('goods_id'=>$goods_id))->find();
        $M_store = $store->field("sc_id,store_id")->where(array('member_id'=>$uid))->find();
        $store_info = $store -> field("sc_id,store_id")->where(array('store_id'=>$goods_info['store_id']))->find();
        $Member_info = $Member->field("member_id,member_name")->where(array('member_id'=>$uid))->find();
        if ($M_store['store_id'] == $goods_info['store_id']){
            returnApiError(1,'不能收藏自己店铺的商品！');
        }
         $data = array_merge($goods_info,$store_info,$Member_info);
         $data['fav_type'] = 'goods';
         $data['fav_time'] = time();
         $data['log_msg'] = $goods_info['log_price'];

        if ($lastInsId = $favorites->add($data)) {
           $goods ->where('goods_id='.$goods_id)->setInc('goods_collect',1);
         returnApiSuccess('收藏成功');
        } else {
         returnApiError(1,'数据写入错误！');
        }

        } 
		
	/**
     * [member 会员信息]
     * @return [type] [json]
     */
	public function member(){
		$uid = I('post.uid',0,'intval');
		$tel = I('post.tel');
		
		//实例化地址信息
		$Member = M('Member');
        if($uid){
            $where['member_id'] = $uid;
        }
        if($tel){
            $where['member_mobile'] = $tel;
        }
		if(!$where) returnApiError(1,'参数错误');
        $field = "member_id,member_name,member_email,member_truename,member_avatar,member_sex,member_birthday,member_mobile,member_qq,member_areainfo,member_qqopenid,member_sinaopenid,weixin_unionid,member_email_bind,member_mobile_bind";
		$data = $Member->field($field)->where($where)->find();

        if(!$data) {

            returnApiError(1,'用户不存在');
        }
		foreach($data as $k=>$v){
            if($v == null){
                $txt = "";
                $data[$k] = $txt;
            }
        }

        $data['member_avatar'] = SHOP_SITE_URL.'/data/upload/shop/avatar/'.$data['member_avatar'] ;
        $data['is_qqbind'] = $data['member_qqopenid'] ? 1 : 0;
        $data['is_sinabind'] = $data['member_sinaopenid'] ? 1 : 0;
        $data['is_wxbind'] = $data['weixin_unionid'] ? 1 : 0;
        returnApiSuccess('ok',$data);

	}


    /**
     * 修改头像
     */
    public function editavatar(){
        $uid = I('post.uid');
       // returnApiSuccess($_POST);die;
        //if(!$uid)   if(!$uid) returnApiError(1,'uid不能为空');
        $config = array(
            'hostname' => 'http://un-eagle.cn',
            'username' => 'userlisten',
            'password' => 'sdfW2Q58i4W3a5Q6',
            'port' => 21
        );

        Vendor('Ftp.ftp');
        $ftp = new \Ftp();
        $ftp->connect($config);


        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->autoSub  =     false; // 设置附件上传（子）目录
        $upload->saveName = "avatar_$uid";

        $string = ($_FILES['upfile']['name']);
        $array = explode('.',$string);
        $ext = end($array);
        $file = $upload->rootPath.$upload->saveName.'.'.$ext;;


        // 上传文件
        $info   =   $upload->uploadOne($_FILES['upfile']);

        if(!$info) {// 上传错误提示错误信息
            if($upload->getError() == ('存在同名文件'.$upload->saveName.'.'.$ext)){
                @unlink ($file);
                $info2   =   $upload->uploadOne($_FILES['upfile']);
                if(!$info2)   returnApiError(1,$upload->getError());
                $ftp->delete_file('web/data/upload/shop/avatar/'.$upload->saveName.'.'.$ext);
                $upfile = $ftp->upload('./Uploads/'.$upload->saveName.'.'.$ext,'web/data/upload/shop/avatar/'.$upload->saveName.'.'.$ext);
                if(!$upfile) returnApiError(1,'ftp上传失败');
                $member = M('member');
                $save['member_avatar'] = $upload->saveName.'.'.$ext;
                $where['member_id'] = $uid;
                $member->where($where)->save($save);
                returnApiSuccess('修改头像成功');
            }
            returnApiError(1,$upload->getError());
        }


        $member = M('member');
        $save['member_avatar'] = $upload->saveName.'.'.$ext;
        $where['member_id'] = $uid;
        $member->where($where)->save($save);
        returnApiSuccess('修改头像成功');

    }


    public function iosavatar(){
       // header("Content-Type: application/octet-stream");
        $path  =  './Uploads/'; // 设置附件上传根目录
        //$path  =  dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/data/upload/shop/avatar/'; // 设置附件上传根目录
        $uid = $_POST['uid'];
        $byte = $_POST['upfile'];
        if(!$byte) {
            returnApiError(1,'没有接收到数据流');
        }
        $byte = str_replace(' ','',$byte);   //处理数据
        $byte = str_ireplace("<",'',$byte);
        $byte = str_ireplace(">",'',$byte);
        $byte = pack("H*",$byte);      //16进制转换成二进制
       // file_put_contents('1.jpg',$byte);//写入文件中！

        $file = fopen($path.'avatar_'.$uid.'.png',"w");//打开文件准备写入
        fwrite($file,$byte);//写入
        fclose($file);//关闭

        $config = array(
            'hostname' => 'http://un-eagle.cn',
            'username' => 'userlisten',
            'password' => 'sdfW2Q58i4W3a5Q6',
            'port' => 21
        );

        Vendor('Ftp.ftp');
        $ftp = new \Ftp();
        $ftp->connect($config);
        $ftp->delete_file('web/data/upload/shop/avatar/avatar_'.$uid.'.png');
        $upfile = $ftp->upload('./Uploads/avatar_'.$uid.'.png','web/data/upload/shop/avatar/avatar_'.$uid.'.png');
        if(!$upfile) returnApiError(1,'ftp上传失败');

        $member = M('member');
        $save['member_avatar'] = 'avatar_'.$uid.'.png';
        $where['member_id'] = $uid;
        $member->where($where)->save($save);

        returnApiSuccess('修改头像成功',SHOP_SITE_URL.'/data/upload/shop/avatar/avatar_'.$uid.'.png');
        die;


    }
	
	/**
     * [editmember 编辑会员信息]
     * @return [type] [json]
     */
	public function editmember(){
		$uid = I('post.uid',0,'intval');
		$member_truename = I('post.truename');   //真实姓名
		$member_sex = I('post.sex');             //1男  2女 3保密
		$member_birthday = I('post.birthday');   //生日
		
		//验证数据
		if(!$uid)   returnApiError(1,'用户id参数错误');
		if(strlen($member_truename) > 20)  returnApiError(1,'姓名长度超过20个字符');
		if(strlen($member_sex) > 3)  returnApiError(1,'性别参数不正确');
		if($member_birthday){
			$is_date = strtotime($member_birthday)?strtotime($member_birthday ):false;
			if(!$is_date) returnApiError(1,'日期格式不正确');
		}
		
		//修改数据
		$Model = M('Member');
		if(!$Model->where("member_id = $uid")->find()) returnApiError(4006,'用户不存在');
		$data['member_truename'] = $member_truename;
		$data['member_sex'] = $member_sex;
		if(!empty($member_birthday)){
			$data['member_birthday'] = $member_birthday;
		}
		$where['member_id'] = $uid;
		if($Model->where($where)->save($data)){
			 returnApiSuccess('ok'); 
		}else{
			 returnApiError(1,'保存失败');
		}
		
	}
	
	/**
     * [pointslog 积分记录]
     * @return [type] [json]
     */
	public function pointslog(){
		$uid = I('post.uid',0,'intval');
		$pindex = I('post.pno',1,'intval') ;     //当前页码
		$psize  = I('post.pgz',10,'intval') ;   //显示条数
		if(!$pindex)  $pindex = 1;
		$pfirst = ($pindex - 1) * $psize;
		$Model = M('Member');
		if(!$Model->where("member_id = $uid")->find()) returnApiError(4006,'用户不存在');
		$Model = M('PointsLog');
		$where['pl_memberid'] = $uid;
		$data = $Model->field("pl_id,pl_memberid,pl_membername,pl_points,pl_desc,pl_addtime")->where($where)->limit($pfirst .','.$psize)->select();
		if(!$data){
			returnApiSuccess('数据为空'); 
		}else{
			returnApiSuccess('ok',$data); 
		}
		
	}
	
	/**
     * [pointsorder 积分兑换订单]
     * @return [type] [json]
     */
	public function pointsorder(){
		$uid = I('post.uid',0,'intval');
		$pindex = I('post.pno',1,'intval') ;     //当前页码
		$psize  = I('post.pgz',10,'intval') ;   //显示条数
		if(!$pindex)  $pindex = 1;
		$pfirst = ($pindex - 1) * $psize;
		$Model = M('Member');
		if(!$Model->where("member_id = $uid")->find()) returnApiError(4006,'用户不存在');
		$Model = M('PointsOrder');
		$where['point_buyerid'] = $uid;
		$data = $Model->where($where)->limit($pfirst .','.$psize)->select();
		if(!$data){
			returnApiSuccess('数据为空'); 
		}else{
			returnApiSuccess('ok',$data); 
		}
	}
	
	/**
     * [pointsgoods 积分商品]
     * @return [type] [json]
     */
	public function pointsgoods(){
		$uid = I('post.uid',0,'intval');
		$pindex = I('post.pno',1,'intval') ;     //当前页码
		$psize  = I('post.pgz',10,'intval') ;    //显示条数
		if(!$pindex)  $pindex = 1;
		$pfirst = ($pindex - 1) * $psize;
		$Model = M('PointsGoods');
		$data = $Model->limit($pfirst .','.$psize)->select();
		if(!$data){
			returnArr('数据为空');
		}else{
			returnApiSuccess('ok',$data); 
		}
	}

    public function  mypoint(){
        $uid = I('uid',0,'intval');
        if(!$uid)   returnApiError(1,'用户id参数错误');
        $Model = M('member');
        $data = $Model->field('member_points')->find($uid);
        returnApiSuccess('ok',$data);

    }

    /**
     *余额
     */
    public function available(){
        $uid = I('post.uid',0,'intval');
        if(!$uid)   returnApiError(1,'用户id参数错误');
        $model = M('member');
        $where['member_id'] = $uid;
        $data = $model->field('available_predeposit,freeze_predeposit,available_rc_balance,freeze_rc_balance')->where($where)->find();
        if(!$data){
            returnArr('数据为空');
        }else{
            returnApiSuccess('ok',$data);
        }

    }

    /**
     * 修改密码
     */
    public function editpass(){
        $uid = I('post.uid',0,'intval');
        $pass = I('post.pass');
        $newpass = I('post.newpass');
        if(!$uid)   returnApiError(1,'用户id参数错误');
        if(!$pass)   returnApiError(1,'缺少pass参数');
        if(!$newpass)   returnApiError(1,'缺少newpass参数');
        $model = M('member');
        $where['member_id'] = $uid;
        $data = $model->where($where)->find();
        if(!$data) returnApiError(1,'用户不存在');

        if($data['member_passwd'] != md5($pass)) returnApiError(1,'密码不正确');
        $save['member_passwd'] = md5($newpass);
        if($model->where($where)->save($save)){
            parent::emchat_resetPassword($data['member_name'],md5($newpass));
            returnApiSuccess('修改密码成功');
        }
        returnApiError(1,'修改失败');
    }
	
	
	/**
     * 设置支付密码
     */
    public function modifypaypwd(){
        $code = intval($_POST['code']);
        $paywd = I('post.paywd');
        $uid = I('post.uid');
        if(!$code) returnApiError(1,'请填写验证码');
        if(!$paywd) returnApiError(1,'请填写支付密码');
        if(!$uid) returnApiError(1,'请填写uid');

        $Model = M('Member');
        $where['member_id'] = $uid;
        $data = $Model->field('member_id,member_avatar,member_name,member_truename,member_mobile,member_login_time,member_old_login_time,member_login_ip')->where($where)->find();
        if(!$data) returnApiError(40006,'用户不存在');
        $tel = $data['member_mobile'];
        if(!$tel) returnApiError(1,'请先绑定手机号');

        //returnApiError(1,'验证码是'.intval($code));

        //短信验证
        $api = 'https://webapi.sms.mob.com/sms/verify';
        $arr = array(
            'appkey' => $this->appkey,
           // 'phone' => 18670951862,
            'phone' => $tel,
            'zone' => '86',
            'code' => $code,
            //'code' => 5732,
        );
       // returnApiSuccess($arr);
       // die;
        $response = $this->postRequest($api, $arr);
        $param = json_decode($response,true);
        $status= $param['status'];
        if($status != 200){
            returnApiError($status,'短信校验失败');
        }
        $uid = $data['member_id'];
        $con = array(
            'member_paypwd' => md5($paywd),
        );
        if($Model->where("member_id = $uid")->save($con)){
            returnApiSuccess('支付密码设置成功');
        }
        returnApiError(1,'支付密码设置成功');
    }
	
  
}